package wk.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import wk.entity.Admin;
import wk.service.impl.AdminServiceImpl;
import wk.utils.md5.MD5Code;
import wk.utils.sms.SendMessageUtil;
import wk.utils.validation.Validater;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("admin")
public class AdminController {

    @Autowired
    private AdminServiceImpl adminService;

    //提供一个用户短信校验的方法
    @RequestMapping("code")
    @ResponseBody
    public JSONObject messageVerify (HttpServletRequest request){
        JSONObject json = new JSONObject();
        String phoneNumber = request.getParameter("phone");
        System.out.println(phoneNumber);
        if(phoneNumber ==null){
            json.put("ret",false);
            json.put("code", 2);
            return json;
        }
        //随机产生六位数字字符串的验证码
        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++)
        {
            result+=random.nextInt(10);
        }
        //获取AES算法加密对象

        System.out.println("加密前的数据："+result);
        SendSmsResponse sendSms = null;
        try {
            sendSms  =  SendMessageUtil.sendSms(phoneNumber, result.toString());
            HttpSession session = request.getSession();
            session.setAttribute("verifyCode",result);
            session.setAttribute("verifyCodeCreateTime",System.currentTimeMillis());
            System.out.println(result);
            System.out.println("短信接口返回的数据----------------");
            System.out.println("Code=" + sendSms.getCode());
            System.out.println("Message=" + sendSms.getMessage());
            System.out.println("RequestId=" + sendSms.getRequestId());
            System.out.println("BizId=" + sendSms.getBizId());

        } catch (ClientException e) {
            e.printStackTrace();
        }

        //这些都是阿里云API替我们发送信息成功后返回的数据


        //判断前端需要发送验证码的手机号码格式是否规范
        if (sendSms.getCode().equals("OK")) {
            //验证码发送成功
            json.put("code", 200);
            json.put("data", result);
            json.put("ret", true);
        } else {
            //验证码发送失败
            json.put("code", 1);
            json.put("data", result);
            json.put("ret", true);
        }
        System.out.println(json);
        return json;
    }

    @RequestMapping("fogotreset")
    @ResponseBody
    public JSONObject fogotreset(HttpServletRequest request,HttpSession session){
        JSONObject jsonResult=new JSONObject();
        String smsvercode=request.getParameter("smsvercode");
        String vercode=request.getParameter("vercode");
        String cellphone=request.getParameter("cellphone");
        try {
            if(session.getAttribute("verifyCodeCreateTime") !=null && (System.currentTimeMillis()-Long.valueOf(String.valueOf(session.getAttribute("verifyCodeCreateTime"))) )> 1000 * 60  ){
                session.removeAttribute("verifyCode");
                session.removeAttribute("verifyCodeCreateTime");
                jsonResult.put("msg","验证码过期");
                jsonResult.put("code",2);

            }
            else if (session.getAttribute("verifyCode") != null &&
                    smsvercode.equals(session.getAttribute("verifyCode"))){
                session.removeAttribute("verifyCode");
                session.removeAttribute("verifyCodeCreateTime");
                session.setAttribute("cellPhone",cellphone);
                jsonResult.put("msg","验证成功");
                jsonResult.put("code",200);
            }else{
                jsonResult.put("msg","验证失败");
                jsonResult.put("code",1);
            }

        }catch(Exception e){
            jsonResult.put("msg","验证码失败");
            jsonResult.put("code",1);
            e.printStackTrace();
        }
        return jsonResult;

    }


    @RequestMapping("passreset")
    @ResponseBody
    public JSONObject passreset(@RequestBody Map<String,String> map, HttpServletRequest request) throws SQLException {
        JSONObject jsonResult=new JSONObject();
        String name=map.get("name");
        String password=map.get("password");
        String repass=map.get("repass");
        HttpSession session=request.getSession(true);
        Admin admin=new Admin();
        admin.setAdminName(name);
        admin.setCellPhone(request.getSession().getAttribute("cellPhone").toString());
        admin=adminService.find(admin);
        if(Validater.validationEmpty(name) || Validater.validationEmpty(password)||
                Validater.validationEmpty(repass)){
            if(admin!=null){
                if(password.equals(repass)){
                    admin.setPassWord((new MD5Code().getMD5ofStr("{" + password + "}")));
                    if(adminService.resetpassword(admin)){
                        jsonResult.put("code",200);
                        jsonResult.put("msg","密码修改成功");
                    }
                }else{
                    jsonResult.put("code",2);
                    jsonResult.put("msg","两次输入的密码不相符");
                }
            }else{
                jsonResult.put("code",1);
                jsonResult.put("msg","用户不存在");
            }

        }
        return jsonResult;

    }
}
